package com.cheung.leetcode.hash;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.hash
 * @Author :  cheungming
 * @CreateTime : 2024-05-03 07:47:31
 * @Description : 438题
 * @Version : 1.0
 */
public class Code438Test {


    public List<Integer> findAnagrams(String s, String p) {

        int sLen = s.length();
        int pLen = p.length();

        if (sLen < pLen) {
            return new ArrayList<>();
        }

        List<Integer> list = new ArrayList<>();

        // 灵茶山艾府 B站刷题up主

        // 统计子串的字符数组
        int[] sArr = new int[26];
        int[] pArr = new int[26];

        for (int i = 0; i < pLen; i++) {
            sArr[s.charAt(i) - 'a']++;
            pArr[p.charAt(i) - 'a']++;

        }
        if (Arrays.equals(sArr, pArr)) {
            list.add(0);
        }

        for (int r = pLen; r < sLen; r++) {
            // 右滑一格，减去最左的一个
            sArr[s.charAt(r - pLen) - 'a']--;
            // 加上当前的一个
            sArr[s.charAt(r) - 'a']++;
            if (Arrays.equals(sArr, pArr)) {
                // 计算左索引
                list.add(r - pLen + 1);
            }
        }


        return list;
    }


    @Test
    public void test1() {
        String s = "cbaebabacd", p = "abc";
        List<Integer> list = findAnagrams(s, p);
        System.out.println(list);
    }

    @Test
    public void test2() {
        String s = "abab", p = "ab";
        List<Integer> list = findAnagrams(s, p);
        System.out.println(list);
    }

    @Test
    public void test3() {
        String s = "aa", p = "bb";
        List<Integer> list = findAnagrams(s, p);
        System.out.println(list);
    }

    @Test
    public void test4() {
        String s = "baa", p = "aa";
        List<Integer> list = findAnagrams(s, p);
        System.out.println(list);
    }
}
